package hibernate.xml43.view;

import hibernate.xml43.pojo.Dept;
import hibernate.xml43.util.HibernateHandler;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

public class View6 {
	
	public static void main(String[] args) {
		
		Session session = HibernateHandler.getSession();

		int pageSize = 3;
		int pageCount = getDeptPageCount(pageSize);
		
		for(int i=1;i<=pageCount;i++){
			System.out.println("------------------第 "+i+" 页------------------");
			pagingDept(pageSize,i);
		}
		
		session.close();
	}
	//根据pageSize获取总页数
	public static int getDeptPageCount(int pageSize){
		Session session = HibernateHandler.getSession();
		String hql = "select count(*) from Dept";
		Object obj = session.createQuery(hql).uniqueResult();
		int sum = Integer.parseInt(obj.toString());
		int pageCount = (sum-1)/pageSize+1;
		session.close();
		return pageCount;
	}
	//分页
	@SuppressWarnings("unchecked")
	public static void pagingDept(int pageSize,int pageNum){
		Session session = HibernateHandler.getSession();
		String hql = "from Dept";
		Query query = session.createQuery(hql)
		.setFirstResult((pageNum-1)*pageSize)
		.setMaxResults(pageSize);
		List<Dept> list = query.list();
		for(Dept d:list){
			System.out.println(d.getDeptno()+"\t"+d.getDname()+"\t"+d.getLoc());
		}
		session.close();
	}
	
	@SuppressWarnings("unchecked")
	public static void query1() {
		Session session = HibernateHandler.getSession();
		//只是演示查询就不使用事务了...
		String hql = "from Dept";
		Query query = session.createQuery(hql)
		//设置从第几条开始取
		.setFirstResult(0)
		//设置取几条
		.setMaxResults(3);
		List<Dept> list = query.list();
		for(Dept d:list){
			System.out.println(d.getDeptno()+"\t"+d.getDname()+"\t"+d.getLoc());
		}
		session.close();
	}
}
